package particles;

import bpmjs.Stats;
import bpmjs.HtmlDef;
import bpmjs.Matrix4;
import bpmjs.Camera;
import bpmjs.Color;

import js.Lib;

import haxe.Timer;

using bpmjs.MooToolsAdapter;

class TestParticles
{
	var matrix : Matrix4;
	var camera : Camera;
	var canvas : Canvas;
	var particles : Array<Particle>;
	
	public static function main()
	{
		try
		{
			new TestParticles();
		}
		catch (e : Dynamic)
		{
			trace("Error launching: " + e);
		}
	}
	
	public function new()
	{
		var content = Lib.document.getElementById("content");
		
		canvas = Lib.document.createCanvas();
		canvas.width = 600;
		canvas.height = 400;
		content.appendChild(canvas);
		
		matrix = new Matrix4();
		matrix.identity();
		
		camera = new Camera();
		camera.tx = 300;
		camera.ty = 200;
		camera.distance = 1000;
		camera.zoom = 0.001;
		
		particles = new Array<Particle>();
		
		var c = 3;
		for(x in -c...c + 1)
		for(y in -c...c + 1)
		for(z in -c...c + 1)
		{
			var particle = new Particle();
			
			particle.x = x * 33;
			particle.y = y * 33;
			particle.z = z * 33;
			particle.size = 30;
			
			particles.push(particle);
		}
		
		var timer = new Timer(Std.int(1000 / 60));
		timer.run = handleTimer;
	}
	
	public function handleTimer()
	{
		Stats.measureFPS();
		
		var context = canvas.getContext2D();
		
		context.clearRect(0, 0, canvas.width, canvas.height);
		context.globalCompositeOperation = "lighter";

		matrix.appendRotation(0.0013, 0.0017, 0.002);
		
		for(particle in particles)
		{
			matrix.transform(particle);
			camera.project(particle);
			
			var alpha = 5 * particle.pz - 5 + 0.5;
			if (alpha < 0)
				alpha = 0;
			if (alpha > 1)
				alpha = 1;
			
			particle.sSize = particle.size * particle.pz; 
			var size = particle.sSize;
			
			//context.fillStyle = "rgba(255,0,0,1)";
			//context.fillRect(particle.px - size / 2, particle.py - size / 2, size, size);
			
			var x = particle.px - size / 2; 
			var y = particle.py - size / 2;
			
			var halfSize = size / 2;
			var sizeSmall = 0;
			var radgrad = context.createRadialGradient( x + halfSize, y + halfSize, sizeSmall, x + halfSize, y + halfSize, halfSize);  
            radgrad.addColorStop( 0, Color.toContextRGBA(255, 255, 0, alpha));
            radgrad.addColorStop( 1, Color.toContextRGBA(0, 0, 0, 0));
            context.fillStyle = radgrad;
            context.fillRect(x,y, size, size );			
		}
	}
}
